<?php
declare (strict_types=1);

namespace app\scan_bag\controller;

use app\admin\model\advertiser\AdvertiserTask;
use app\admin\model\advertiser\AdvertiserTaskLog;
use app\admin\model\advertiser\AdvertiserThird;
use app\admin\model\advertiser\AdvertiserThirdLog;
use app\admin\model\base\User;
use app\admin\model\base\UserOfficial;
use app\admin\model\iot\AdvertiserTaskDevice;
use app\admin\model\iot\ScanBagDay;
use app\admin\model\iot\ScanBagWay;
use app\admin\service\base\JwtService;
use app\BaseController;
use app\BaseService;
use app\scan_bag\service\ScanBagV1Service;
use app\scan_bag\service\ScanBagV2Service;
use app\scan_bag\service\V1_Way_1_0Service;
use think\App;
use think\facade\Cache;
use think\facade\Log;
use think\response\Json;
use wechat\ScanBagMiniProgram;
use wechat\WsOfficialAccount;
use wechat\WsOpenPlatform;
use app\admin\model\iot\ScanBagStrategy as ScanBagStrategyModel;

/**
 * 微信LCV2_0扫码取袋
 */
class LCV2_0 extends BaseController
{

    /**
     * 当前扫码路径
     * @var string
     */
    private string $way = 'LCV2_0';

    /**
     * 微信H5用户登录
     * @param ScanBagV2Service $scanBagV2Service
     * @return Json
     */
    public function wechatLogin(ScanBagV2Service $scanBagV2Service): Json
    {
        //接受参数
        $code = $this->request->param('code/s', '');
        //微信解析code
        $bool = $scanBagV2Service->wechatH5Login2($code);
        if ($bool['bool']) {
            //签发token
            $jst_data = JwtService::authorizations('scan_bag', $bool['user_id'], 3600);
            if ($jst_data['bool']) {
                return jsonReturn(1, $bool, '登录成功');
            }
        }
        return jsonReturn(0, [], '签发token失败');
    }

    /**
     * 微信H5用户取袋次数
     * @return Json
     */
    public function userScanNum(): Json
    {
        $user_id = WS_USER_ID;
        $day = ScanBagDay::getUserIdDayNum($user_id);
        return jsonReturn(1, $day);
    }

    /**
     * 获取JSAPI配置
     * @return Json
     */
    public function jsApiConfig(): Json
    {
        //接受参数
        $url = $this->request->param('url/s', '');
        $obj = new WsOfficialAccount();
        $data = $obj->getJsApi($url);;
        return jsonReturn(1, $data);
    }

    /**
     * 获取推广微信小程序
     * @return Json
     */
    public function getWechatApplet(): Json
    {
        //接收参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id', '');
        $day_used = $this->request->param('day_used', '');
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        $arr = [1=>'first',2=>'second',3=>'third'];
        if($day_used>3 || $day_used<0){
            $day_used = 3;
        }
        //获取取袋路径
        $WayInfo = ScanBagStrategyModel::getMacIdWay($mac_id,$arr[$day_used]);
        //判断需要验证取袋路径
        if ($WayInfo and $WayInfo['third_mini']) {
            //获取推广小程序信息
            $Third = AdvertiserThird::getIDThird($WayInfo['third_mini']);
            $User = User::getIdUserInfo($user_id);
            $way_code = ScanBagV2Service::generateBagOutWaycode($User, $WayInfo['key'], $mac_id);
            if ($Third and !in_array($mac_id, $Third['prohibit']) and $Third['mini_ogh'] and $Third['mini_appid']) {
                $temp = [
                    'way' => $WayInfo['key'],
                    'third_id' => $Third['id'],
                    'type' => $Third['type'],
                    'mini_name' => $Third['mini_name'],
                    'mini_ogh' => $Third['mini_ogh'],
                    'mini_appid' => $Third['mini_appid'],
                    'mini_link' => $Third['mini_link'],
                    'way_code'=>$way_code
                ];
                //写入统计
                AdvertiserThirdLog::writeMiniprogramLog($user_id, $Third['id'], $mac_id);
                //标记取袋安全码
                $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 1);
                if (!$SafeCode) {
                    return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
                }
                return jsonReturn(1, $temp);
            }
        }
        return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
    }


    /**
     * 微信上传经纬度信息
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function wechatLatLon(V1_Way_1_0Service $v1_Way_1_0Service): Json
    {
        //接受参数
        $mac_id = $this->request->param('mac_id/s', '0');
        $latitude = $this->request->param('latitude/s', '0');
        $longitude = $this->request->param('longitude/s', '0');
        $accuracy = $this->request->param('accuracy/d', 0);    //位置精度
        //经纬度保存数据库
        $user_id = WS_USER_ID;
        //把地理位置信息保存至用户表
        User::userLocationRedis($user_id, $mac_id, $latitude, $longitude);
        //微信验证上传经纬度信息
        $bool = $v1_Way_1_0Service->wechatLatLon($mac_id, $latitude, $longitude);
        if ($bool) {
            return jsonReturn(1, [], '验证通过');
        }
        return jsonReturn(0, [], '您的位置距离设备太远,请移步设备前扫码免费领取。');
    }

    /**
     * 微信小程序URLScheme
     * @return Json
     */
    public function getURLScheme(): Json
    {
        //接收参数
        $params = $this->request->param();
        if (!isset($params['mac_id']) or !$params['mac_id']) {
            return jsonReturn(0, [], '设备参数错误,请联系管理员!');
        }
        //获取用户信息
        $user_id = WS_USER_ID;
        $User = User::getIdUserInfo($user_id);
        $params['open_id'] = $User['openid'];
        //通过mac_id获取路径
        $WayInfo = ScanBagWay::getMacIdWay($params['mac_id']);
        if ($WayInfo['key'] != $this->way) {
            return jsonReturn(0, [], '路径参数错误,请联系管理员');
        }
        //生成取袋路径微信小程序码
        $wechat = new ScanBagMiniProgram($WayInfo);
        $path = $WayInfo['mini_link'] ?? 'pages/index/index';
        //增加取袋码
        $params['way'] = $WayInfo['key'];
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $params['mac_id'], 3,true);
        if (!$SafeCode) {
            $params['waycode'] = rand(100000,999999);
        }else{
            $params['waycode'] = ScanBagV2Service::generateBagOutWaycode($User, $WayInfo['key'], $params['mac_id']);
        }

        //收到打开时需要的参数
        $data['miniPath'] = $path . '?' . http_build_query(array_unique($params));
        //则生成取袋路径微信小程序码
        $data['scheme'] = $wechat->URLScheme($path, http_build_query($params));
        $code = $data['scheme']['bool'] ? 1 : 0;
        return jsonReturn($code, $data);
    }

    /**
     * 微信取袋码出袋
     * @param ScanBagV1Service $scanBagV1Service
     * @param V1_Way_1_0Service $v1_Way_1_0Service
     * @return Json
     */
    public function postOutBag(): Json
    {
        //接收参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id/s', '');
        $waycode = $this->request->param('way_code/s', '');
        $sleep = $this->request->param('sleep/d', 15);
        $location_limit = $this->request->param('location_limit/d', 0);
        //判断缓存是否有策略
        $tKey = BaseService::generateScanBagStrategyKey($user_id);
        $WayInfo = Cache::get($tKey);
        if($WayInfo){
            $location_limit = json_decode($WayInfo,true)['location_limit'];
        }
        //判断参数
        if (!$user_id or !$mac_id or !$waycode) {
            return jsonReturn(0, [], '参数错误');
        }
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 2, true);
        if (!$SafeCode) {
            return jsonReturn(0, [], '请重新扫描设备二维码!');
        }
        //暂时隐藏地理位置限制
//        if($location_limit){
//            //获取缓存当前用户经纬度
//            $LatLon = Cache::get(BaseService::generateLocationKey($user_id));
//            if (!$LatLon or !isset($LatLon['latitude']) or !isset($LatLon['longitude'])) {
//                return jsonReturn(0, [], '您的位置授权失败,请重新扫描设备二维码!');
//            }
//            //验证地理位置
//            $bool = ScanBagV2Service::verifyLatLon($mac_id, $LatLon['latitude'], $LatLon['longitude']);
//            if (!$bool) {
//                return jsonReturn(0, [], '您的位置距离设备太远,请移步设备前扫码免费领取!');
//            }
//        }
        //执行出袋程序
        $res = ScanBagV2Service::bagOutProgram($waycode, $this->way, $user_id, $mac_id,1);
        if ($res['bool']) {
            return jsonReturn(1, $res['data'], $res['msg']);
        }
        return jsonReturn(0, [], $res['msg']);
    }

    /**
     * 发起微信支付
     * @param ScanBagV1Service $scanBagV1Service
     * @return Json
     */
    public function wechatPayOrder(ScanBagV1Service $scanBagV1Service): Json
    {
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id');
        if (!$mac_id) {
            return jsonReturn(0, [], '设备信息错误');
        }
        return $scanBagV1Service->payOrderToV1($user_id, $mac_id);
    }

    /**
     * 判断是否打开位置限制
     * @return Json
     */
    public function locationLimit():Json
    {
        $mac_id = $this->request->param('mac_id/s','');
        $day_used = $this->request->param('day_used', 0);
        //判断参数
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        $arr = [1=>'first',2=>'second',3=>'third'];
        if($day_used>3 || $day_used<0){
            $day_used = 3;
        }
        //获取取袋路径
        $WayInfo = ScanBagStrategyModel::getMacIdWay($mac_id,$arr[$day_used]);
        if($WayInfo && $WayInfo['location_limit']){
            return jsonReturn(1, ['location_limit'=>$WayInfo['location_limit']]);
        }
        return jsonReturn(1, ['location_limit'=>0]);
    }


}
